package com.puboot;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;

import java.io.File;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;

/**
 * @author LinZhaoguan
 * @version V1.0
 * @date 2019年9月11日
 */
@Slf4j
@SpringBootApplication
public class SpringbootApplication {

    public static void main(String[] args) throws Exception {
        doStart(args);
    }


    /**
     * 开始启动
     *
     * @param args
     * @throws Exception
     */
    public static void doStart(String[] args) throws Exception {

        // 获取当前线程的PID
        getPID();

        ConfigurableApplicationContext application = SpringApplication.run(SpringbootApplication.class, args);

        Environment env = application.getEnvironment();
        String ip = InetAddress.getLocalHost().getHostAddress();
        String port = env.getProperty("server.port");
        String contextPath = env.getProperty("server.servlet.context-path");
        if (contextPath == null) {
            contextPath = "";
        }
        log.info("\n----------------------------------------------------------\n\t" +
                "Application is running! Access URLs:\n\t" +
                "Local: \t\thttp://localhost:" + port + contextPath + "\n\t" +
                "External: \thttp://" + ip + ':' + port + contextPath + '\n' +
                "----------------------------------------------------------");

        // 如果执行了kill -15 pid ,则会执行该钩子
        closeHook();

        // 在交互模式下读取用户输入
        //readInput();
    }


    /**
     * 钩子
     */
    private static void closeHook() {
        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                System.out.println("jvm is closing...");
            }
        });
    }


    /**
     * 获取当前程序的PID
     *
     * @throws Exception
     */
    private static void getPID() throws Exception {
        // get name representing the running Java virtual machine.
        String name = ManagementFactory.getRuntimeMXBean().getName();
        // get pid
        final String pid = name.split("@")[0];
        System.out.println("Pid is:" + pid);

        // 获取上下文路径
        URL url = SpringbootApplication.class.getResource("");
        System.out.println("cotextPath:" + url);
        if (url != null) {
            String cotextPath = url.getPath();
            if (cotextPath.contains(".jar!")) {// 说明是jar包
                cotextPath = cotextPath.substring(0, cotextPath.indexOf("!"));
                cotextPath = cotextPath.substring(0,
                        cotextPath.lastIndexOf("/"));
            } else {// 不然从线程里得
                url = Thread.currentThread().getContextClassLoader()
                        .getResource("");
                if (url != null) {
                    cotextPath = url.getPath();
                } else {
                    throw new Exception("无法生成PID文件");
                }
            }
            if (cotextPath.contains("file:")) {// 针对windows的情况
                cotextPath = cotextPath.replace("file:", "");
            }

            // String cotextPath = "/var/run/";
            System.out.println("cotextPath:" + cotextPath);

            // 写PID文件
            FileUtils.writeStringToFile(new File(cotextPath + "/cms.pid"), pid, "UTF-8");
        }
    }
}
